package com.lwq.imserver.service;

import com.lwq.imserver.model.*;
import com.lwq.imserver.util.WebSocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2022/1/20 15:17
 */
@Service
@Slf4j
public class MessageService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public Object listPage(Long timestamp, String roomId, Integer page, Integer size) {
        Criteria where = new Criteria();
        Query query = new Query(where);
        where.and("roomId").is(roomId);
        if (timestamp != null) {
            where.and("timestamp").lt(timestamp);
        }
        Long count = mongoTemplate.count(query, ChatMessage.class);
        query.skip((page - 1) * size);
        query.limit(size);
        List<ChatMessage> chatMessagePage = mongoTemplate.find(query.with(Sort.by(Sort.Direction.DESC, "timestamp")), ChatMessage.class);
        Collections.reverse(chatMessagePage);
        PageModel pageModel = new PageModel();
        pageModel.setData(chatMessagePage);
        pageModel.setCount(count);
        if (count < size.longValue()) {
            pageModel.setAllPages(1L);
            pageModel.setIsLast(true);
        } else {
            Long temp;
            if (count % size != 0) {
                temp = (count / size) + 1;
            } else {
                temp = count / size;
            }
            pageModel.setAllPages(count.equals(size.longValue()) ? 1 : temp);
        }
        return pageModel;
    }

    public void login() {
        WebSocketUtil.broadCast(new SendBody(SendBody.LOGIN));
    }

    public void logout() {
        WebSocketUtil.broadCast(new SendBody(SendBody.LOGOUT));
    }

    public List<ChatMessage> add(ReplyBody replyBody) {
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage();
        BeanUtils.copyProperties(replyBody, chatMessage);
        chatMessage.setTimestamp(Calendar.getInstance().getTimeInMillis());
        messages.add(chatMessage);
        if (!replyBody.getImgUrls().isEmpty()) {
            for (String url : replyBody.getImgUrls()) {
                String content = messages.get(0).getContent();
                ChatMessage temp = new ChatMessage();
                BeanUtils.copyProperties(chatMessage,temp);
                messages.get(0).setContent(content.replaceAll("<img class=\"content-img\" src=\""+url+"\"/>",""));
                temp.setContent("<img class=\"content-img\" src=\""+url+"\"/>");
                temp.setTimestamp(Calendar.getInstance().getTimeInMillis());
                temp.setId(null);
                messages.add(temp);
            }
        }
        mongoTemplate.insertAll(messages);
        return messages;
    }

    public void del(ReplyBody replyBody) {
        mongoTemplate.remove(Query.query(Criteria.where("id").is(replyBody.getId())), ChatMessage.class);
        WebSocketUtil.broadCast(handleSendBody(replyBody));
    }

    public void send(ReplyBody replyBody) throws InterruptedException {
        if (StringUtils.isEmpty(replyBody.getContent())) {
            log.error("输入内容为空");
            return;
        }
        Boolean saveFlag = false;
        List<SendBody> sendBodies = new ArrayList<>();
        try {
            List<ChatMessage> models = add(replyBody);
            saveFlag = true;
            for(ChatMessage chatMessage: models){
                SendBody sendBody = handleSendBody(replyBody);
                sendBody.setContent(chatMessage.getContent());
                sendBody.setId(chatMessage.getId());
                sendBody.setTimestamp(chatMessage.getTimestamp());
                sendBodies.add(sendBody);
            }
//            replyBody.setId(model.getId());
//            replyBody.setTimestamp(model.getTimestamp());
        } catch (Exception e) {
            log.error("保存出现异常:==" + e.getMessage());
        }
        if (!saveFlag) return;
        if (replyBody.getSingle().equals(TransferModel.SINGLE)) {
            for (SendBody sendBody: sendBodies){
                WebSocketUtil.singleCast(sendBody);
                Thread.sleep(50);
            }
        } else if (replyBody.getSingle().equals(TransferModel.GROUP)) {
            for (SendBody sendBody: sendBodies){
                WebSocketUtil.broadCast(sendBody);
                Thread.sleep(100);
            }
        }
    }

    /**
     * 进来的实体和出去的实体转换
     *
     * @param replyBody
     * @return
     */
    private SendBody handleSendBody(ReplyBody replyBody) {
        SendBody sendBody = new SendBody();
        BeanUtils.copyProperties(replyBody, sendBody);
        return sendBody;
    }
}
